<?php

namespace App\Http\Controllers\PayInfo;

use Illuminate\Support\Facades\Log;

/**
 * 微信公众号支付
 * @author admin
 *
 */
class WechatPayController extends  CommonController
{
    protected $mch_id = '1497771792';          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
    protected $appid = '';  //公众号APPID 通过微信支付商户资料审核后邮件发送
    protected $apiKey = 'db91fc73a9bc131922527c3d86f7f499';   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
    //protected $appKey = '3c847a50c00280aebe8616bcd67c20c2'; //微信公众号 appSecret

    protected $open_id;    //用户openid
    protected $out_trade_no; //订单号
    protected $body;
    protected $total_fee; //单位 分
    // private   $code;//用户登录凭证（有效期五分钟）。开发者需要在开发者服务器后台调用 api，使用 code 换取 openid 和 session_key 等信息

    protected $book_home_notify_url = ''; //自定义的回调程序地址id  图书到家订单
    protected $goods_notify_url = ''; //自定义的回调程序地址id   商品回调
    protected $owe_notify_url = ''; //自定义的回调程序地址id   缴纳欠款回调
    protected $online_registration_notify_url = ''; //自定义的回调程序地址id   在线办证回调

    protected $type = ''; //类型 book 书籍  goods  商品  owe 欠费

    //public function __construct($out_trade_no ='',$body ='',$total_fee ='' , $code='' , $open_id =1)
    public function __construct($out_trade_no = '', $body = '', $total_fee = '', $open_id = '', $type = 'book')
    {
        parent::__construct();

        $this->appid = config('other.appid'); //微信公众号appid


        $this->out_trade_no = $out_trade_no;    //商户订单号
        $this->body = $body;                    //商品简单描述
        $this->total_fee = $total_fee;          //订单总金额，单位为分
        $this->open_id = $open_id;              //用户open_id
        // $this->code = $code;                    //用户登录凭证（有效期五分钟）

        $this->type = $type;                    //类型，主要区分回调函数用

        $this->book_home_notify_url = config('other.host_url') . 'port/WechatPay/bookHomeNotifyUrl'; //自定义的回调程序地址id（图书到家）
        $this->goods_notify_url = config('other.host_url') . 'port/WechatPay/goodsNotifyUrl'; //自定义的回调程序地址id（商品支付）
        $this->owe_notify_url = config('other.host_url') . 'port/WechatPay/oweNotifyUrl'; //自定义的回调程序地址id（欠费支付）
        $this->online_registration_notify_url = config('other.host_url') . 'port/WechatPay/onlineRegistrationNotifyUrl'; //自定义的回调程序地址id（在线办证支付）
    }



    //外部支付接口
    public function pay()
    {
        //统一下单接口
        $return = $this->weixinapp();

        if (isset($return['return_code']) && $return['return_code'] == 'FAIL') {
            Log::error('订单号：'.$this->out_trade_no.'；下单失败：'.$return['return msg']);
            return false;
        }

        return $return;
    }

    //统一下单接口
    private function unifiedorder()
    {
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';

        //   $openId = $this->getOpendId();

        $body = $this->body;
        $body_num = strlen($body);
        if ($body_num > 128) {
            $body = mb_substr($body, 0, 25); //body字符不能超过128个字符，这里截取一部分
        }

        //回调地址
        if ($this->type == 'goods') {
            $notify_url = $this->goods_notify_url; //商品支付
        } elseif ($this->type == 'owe') {
            $notify_url = $this->owe_notify_url; //欠费支付
        } elseif ($this->type == 'online_registration') {
            $notify_url = $this->online_registration_notify_url; //在线办证支付
        } else {
            $notify_url = $this->book_home_notify_url; //默认图书到家支付
        }

        $parameters = array(
            'appid'         => $this->appid, //小程序ID
            'mch_id'        => $this->mch_id, //商户号
            'nonce_str'     => $this->createNoncestr(), //随机字符串
            'attach'        => 'pay',             //商家数据包，原样返回，如果填写中文，请注意转换为utf-8
            'body'          => $body, //商品描述
            'out_trade_no'  => $this->out_trade_no, //商户订单号
            'total_fee'     => $this->total_fee, //总金额 单位 分
            //            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], //终端IP
            'spbill_create_ip' => '0.0.0.0', //终端IP
            'notify_url'    => $notify_url, //通知地址  确保外网能正常访问
            'openid'        => $this->open_id, //用户id
            'trade_type'    => 'JSAPI' //交易类型
        );


        //统一下单签名
        $parameters['sign'] = $this->getSign($parameters);
        $xmlData = $this->arrayToXml($parameters);

        $return = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));

        return $return;
    }

    /**
     * 获取 用户 openid，用户支付
     */
    private  function getOpendId()
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->appid . '&secret=' . $this->appSecret . '&js_code=' . $this->code . '&grant_type=authorization_code';
        $data = $this->postXmlCurl(' ', $url);
        $data = json_decode($data, true);
        return $data['openid'];
    }

    private static function postXmlCurl($xml, $url, $second = 30)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        if (!empty($xml)) {
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        }

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($ch, CURLOPT_TIMEOUT, 40);
        set_time_limit(0);


        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            throw new \Exception("curl出错，错误码:$error");
        }
    }


    //数组转换成xml
    private function arrayToXml($arr)
    {
        $xml = "<root>";
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $xml .= "<" . $key . ">" . $this->arrayToXml($val) . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }
        }
        $xml .= "</root>";
        return $xml;
    }


    //xml转换成数组
    private function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring), true);
        return $val;
    }


    //微信公众号接口
    private function weixinapp()
    {
        //统一下单接口
        $unifiedorder = $this->unifiedorder();
        // dump($unifiedorder);die;
        if ($unifiedorder['return_code'] !== 'SUCCESS' || $unifiedorder['result_code'] !== 'SUCCESS') {
            return $unifiedorder; //失败
        }

        $parameters = array(
            'appId' => $this->appid, //小程序ID
            'timeStamp' => '' . time() . '', //时间戳
            'nonceStr' => $this->createNoncestr(), //随机串
            'package' => 'prepay_id=' . $unifiedorder['prepay_id'], //数据包
            'signType' => 'MD5' //签名方式
        );
        //签名
        $parameters['paySign'] = $this->getSign($parameters);
        return $parameters;
    }


    //作用：产生随机字符串，不长于32位
    private function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }


    //作用：生成签名
    private function getSign($Obj)
    {
        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . $this->apiKey;
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        return $result_;
    }


    ///作用：格式化参数，签名过程需要使用
    private function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }


    /**
     * 自主查询微信接口，订单是否支付成功
     * @param order_number   订单号
     */
    public function checkWxOrderPay()
    {
        header("Content-type: text/html; charset=utf-8");
        $url = "https://api.mch.weixin.qq.com/pay/orderquery";

        $onoce_str = $this->createNoncestr(32);

        $data["appid"] = $this->appid;
        $data["mch_id"] = $this->mch_id;
        $data["out_trade_no"] = $this->out_trade_no;
        $data["nonce_str"] = $onoce_str;

        $s = $this->getSign($data, false);
        $data["sign"] = $s;

        $xml = $this->arrayToXml($data);
        $response = $this->postXmlCurl($xml, $url);

        $ruturnOut = json_encode(simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA));
        $outType = json_decode($ruturnOut, true); //将微信返回的结果xml转成数组
        //$aString = '$a = '.var_export($outType, true).';';

        //验证正确性
        if ($outType['return_code'] == 'SUCCESS' && $outType['result_code'] == 'SUCCESS' && $outType['trade_state'] == 'SUCCESS') {
            //成功
            return $outType; //直接把订单信息返回
        } else {
            //失败
            //获取错误代码
            /* $error = $outType['result_code'];//FAIL
             * $error_msg = $outType['err_code_des'];//错误消息*/
            return false;
        }
    }

    /**
     * 异步回调地址
     */
    public function bookHomeNotifyUrl()
    {
        $postXml = file_get_contents("php://input");
        // file_put_contents(__DIR__."/".date('Y-m-d H:i:s')."a.txt",$postXml);
        if (empty($postXml)) {
            return false;
        }
        $ruturnOut = json_encode(simplexml_load_string($postXml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $postObj = json_decode($ruturnOut);      // 将xml数据解析成对象

        // file_put_contents(__DIR__."/".date('Y-m-d H:i:s')."a.txt",$ruturnOut);
        if ($postObj === false) {
            return false;
        }
        if (!empty($postObj->return_code)) {
            if ($postObj->return_code == 'FAIL') {
                return false;
            }
        }
        //	return $postObj;          // 返回结果对象；
        $order_number = $postObj->out_trade_no; //商户订单号

        //判断订单是否已经完毕，避免微信重复异步回调
        $result = Db::name('new_order')->select('id,is_pay')->where('order_number', $order_number)->first();

        if (empty($result)) {
            $return = '<xml>
                            <return_code><![CDATA[SUCCESS]]></return_code>
                            <return_msg><![CDATA[OK]]></return_msg>
                        </xml>';

            return $return;
            //订单不存在
            die;
        } else if ($result['is_pay'] != 1) {

            $return = "<xml>
                          <return_code><![CDATA[SUCCESS]]></return_code>
                          <return_msg><![CDATA[OK]]></return_msg>
                        </xml>";

            return  $return;
            //告知微信无需在异步通知
        }

        //微信支付订单号
        $trade_no = $postObj->transaction_id;
        //订单支付时间
        $time_end = $postObj->time_end;
        //转换为时间戳
        $gtime = strtotime($time_end);
        $gmt_payment = date("Y-m-d H:i:s", $gtime); //转换为日期时间格式
        //买家微信支付分配的终端设备号，
        //  $buyer_id  = $postObj->device_info;
        //买家微信账号
        //	$buyer_login_id  = $_POST['buyer_login_id'];
        //订单总金额,订单总金额，单位为分
        $total_amount =  $postObj->total_fee;
        //实收金额,商家在交易中实际收到的款项
        $receipt_amount =  $postObj->total_fee; //微信的实收与总金额一致
        //付款金额,现金支付金额订单现金支付金额，详见支付金额
        $buyer_pay_amount =  $postObj->cash_fee;

        //此处编写回调处理逻辑
        $where = array(
            'order_number' =>  $order_number,
            'pay_time'    => $gmt_payment,
            'payment'    => 1,
            'trade_no'    => $trade_no,
            // 'buyer_id'		=> $buyer_id,
            'total_amount' => $total_amount,
            'receipt_amount' => $receipt_amount,
            'buyer_pay_amount' => $buyer_pay_amount,
        );
        //	file_put_contents(__DIR__."/b.txt",$where);
        //开启事务
        DB::beginTransaction();
        try {
            Db::name('new_order')->where('id', $result['id'])->update(array('is_pay' => 2, 'change_time' => $gmt_payment));
            Db::name('new_order_pay')->insert($where);

            //添加推送信息
            $payInfoObj = new PayInfo();
            $order_info = BookHomeOrderModel::where('order_number', $order_number)->find();
            $payInfoObj->modifySchoolbagState($order_info);

            DB::commit();
            $return = '<xml>
                        <return_code><![CDATA[SUCCESS]]></return_code>
                        <return_msg><![CDATA[OK]]></return_msg>
                    </xml>';
            return $return; //响应表示业务处理成功，告知微信无需在异步通知
        } catch (\Exception $e) {
            DB::rollBack();
        }
        //处理成功一定要返回 success 这7个字符组成的字符串，
        //die('success');//响应success表示业务处理成功，告知微信无需在异步通知
    }


    /**
     * 商品支付成功异步回调地址
     */
    public function goodsNotifyUrl()
    {
        $postXml = file_get_contents("php://input");
        // file_put_contents(__DIR__."/".date('Y-m-d H:i:s')."a.txt",$postXml);
        if (empty($postXml)) {
            return false;
        }
        $ruturnOut = json_encode(simplexml_load_string($postXml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $postObj = json_decode($ruturnOut);      // 将xml数据解析成对象

        //  file_put_contents(__DIR__."/".date('Y-m-d H:i:s')."a.txt",$ruturnOut);
        if ($postObj === false) {
            return false;
        }
        if (!empty($postObj->return_code)) {
            if ($postObj->return_code == 'FAIL') {
                return false;
            }
        }
        //	return $postObj;          // 返回结果对象；
        $order_number = $postObj->out_trade_no; //商户订单号

        //判断订单是否已经完毕，避免微信重复异步回调
        $result = Db::name('goods_order')->select('id,score,is_pay')->where('order_number', $order_number)->first();

        if (empty($result) || empty($result['score']) || $result['is_pay'] != 1) {
            $return = '<xml>
                            <return_code><![CDATA[SUCCESS]]></return_code>
                            <return_msg><![CDATA[OK]]></return_msg>
                        </xml>';

            return $return;
            //订单不存在
            die;
        }

        //微信支付订单号
        $trade_no = $postObj->transaction_id;
        //订单支付时间
        $time_end = $postObj->time_end;
        //转换为时间戳
        $gtime = strtotime($time_end);
        $gmt_payment = date("Y-m-d H:i:s", $gtime); //转换为日期时间格式
        //买家微信支付分配的终端设备号，
        //  $buyer_id  = $postObj->device_info;
        //买家微信账号
        //	$buyer_login_id  = $_POST['buyer_login_id'];
        //订单总金额,订单总金额，单位为分
        $total_amount =  $postObj->total_fee;
        //实收金额,商家在交易中实际收到的款项
        $receipt_amount =  $postObj->total_fee; //微信的实收与总金额一致
        //付款金额,现金支付金额订单现金支付金额，详见支付金额
        $buyer_pay_amount =  $postObj->cash_fee;

        //此处编写回调处理逻辑
        $where = array(
            'order_number' =>  $order_number,
            'pay_time'    => $gmt_payment,
            'payment'    => 1,
            'trade_no'    => $trade_no,
            // 'buyer_id'		=> $buyer_id,
            'total_amount' => $total_amount,
            'receipt_amount' => $receipt_amount,
            'buyer_pay_amount' => $buyer_pay_amount,
        );
        //	file_put_contents(__DIR__."/b.txt",$where);
        //开启事务
        DB::beginTransaction();
        try {
            $goods_id = Db::name('goods_order')->where('id', $result['id'])->value('goods_id');
            $cancel_end_time = Db::name('goods')->where('id', $goods_id)->value('cancel_end_time');
            $cancel_end_time = empty($cancel_end_time)  ? date('Y-m-d H:i:s') : date('Y-m-d H:i:s', strtotime("+" . $cancel_end_time . " min"));

            Db::name('goods_order')
                ->where('id', $result['id'])
                ->update(array('is_pay' => 2, 'change_time' => $gmt_payment, 'cancel_end_time' => $cancel_end_time));

            Db::name('goods_order_pay')->insert($where);

            //添加推送信息
            $payInfoObj = new GoodsPayInfo();
            $order_info = GoodsOrderModel::where('order_number', $order_number)->find();
            $payInfoObj->modifyGoodsState($order_info);


            DB::commit();
            $return = '<xml>
                        <return_code><![CDATA[SUCCESS]]></return_code>
                        <return_msg><![CDATA[OK]]></return_msg>
                    </xml>';
            return $return; //响应表示业务处理成功，告知微信无需在异步通知
        } catch (\Exception $e) {
            DB::rollBack();
        }
        //处理成功一定要返回 success 这7个字符组成的字符串，
        //die('success');//响应success表示业务处理成功，告知微信无需在异步通知
    }


    /**
     * 欠款支付成功异步回调地址
     */
    public function oweNotifyUrl()
    {
        $postXml = file_get_contents("php://input");
        // file_put_contents(__DIR__."/".date('Y-m-d H:i:s')."a.txt",$postXml);
        if (empty($postXml)) {
            return false;
        }
        $ruturnOut = json_encode(simplexml_load_string($postXml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $postObj = json_decode($ruturnOut);      // 将xml数据解析成对象

        //  file_put_contents(__DIR__."/".date('Y-m-d H:i:s')."a.txt",$ruturnOut);
        if ($postObj === false) {
            return false;
        }
        if (!empty($postObj->return_code)) {
            if ($postObj->return_code == 'FAIL') {
                return false;
            }
        }
        //	return $postObj;          // 返回结果对象；
        $order_number = $postObj->out_trade_no; //商户订单号

        //判断订单是否已经完毕，避免微信重复异步回调
        $result = Db::name('owe_order')->select('id', 'is_pay', 'user_id', 'account_id', 'price')->where('order_number', $order_number)->first();

        if (empty($result) || $result['is_pay'] != 1) {
            $return = '<xml>
                            <return_code><![CDATA[SUCCESS]]></return_code>
                            <return_msg><![CDATA[OK]]></return_msg>
                        </xml>';

            return $return;
            //订单不存在
            die;
        }

        //微信支付订单号
        $trade_no = $postObj->transaction_id;
        //订单支付时间
        $time_end = $postObj->time_end;
        //转换为时间戳
        $gtime = strtotime($time_end);
        $gmt_payment = date("Y-m-d H:i:s", $gtime); //转换为日期时间格式
        //买家微信支付分配的终端设备号，
        //  $buyer_id  = $postObj->device_info;
        //买家微信账号
        //	$buyer_login_id  = $_POST['buyer_login_id'];
        //订单总金额,订单总金额，单位为分
        $total_amount =  $postObj->total_fee;
        //实收金额,商家在交易中实际收到的款项
        $receipt_amount =  $postObj->total_fee; //微信的实收与总金额一致
        //付款金额,现金支付金额订单现金支付金额，详见支付金额
        $buyer_pay_amount =  $postObj->cash_fee;

        //此处编写回调处理逻辑
        $where = array(
            'order_number' =>  $order_number,
            'pay_time'    => $gmt_payment,
            'payment'    => 1,
            'trade_no'    => $trade_no,
            // 'buyer_id'		=> $buyer_id,
            'total_amount' => $total_amount,
            'receipt_amount' => $receipt_amount,
            'buyer_pay_amount' => $buyer_pay_amount,
        );
        //	file_put_contents(__DIR__."/b.txt",$where);
        //开启事务
        DB::beginTransaction();
        try {
            Db::name('owe_order')->where('id', $result['id'])->update(array('is_pay' => 2, 'change_time' => $gmt_payment));
            Db::name('owe_order_pay')->insert($where);

            //添加推送信息
            $owePayInfoObj = new \app\port\controller\OwePayInfo();
            $owePayInfoObj->pushMsg($result);

            $fin_account_id_arr = Db::name('owe_order_record')->where('order_id', $result['id'])->column('fin_account_id');
            //处理真实数据
            $yzLibObj = new YzqLib;
            $account = Db::name('user_account_lib')->where('id', $result['account_id'])->value('account');
            $res = $yzLibObj->payArrears($account, $fin_account_id_arr, 1); //修改真实数据
            if ($res['code'] !== 200) {
                throw new Exception('处理失败');
            }

            DB::commit();
            $return = '<xml>
                        <return_code><![CDATA[SUCCESS]]></return_code>
                        <return_msg><![CDATA[OK]]></return_msg>
                    </xml>';
            return $return; //响应表示业务处理成功，告知微信无需在异步通知
        } catch (\Exception $e) {
            DB::rollBack();
        }
        //处理成功一定要返回 success 这7个字符组成的字符串，
        //die('success');//响应success表示业务处理成功，告知微信无需在异步通知
    }


    /**
     * 在线办证押金支付成功异步回调地址
     */
    public function onlineRegistrationNotifyUrl()
    {
        $postXml = file_get_contents("php://input");
        //  file_put_contents(__DIR__."/".date('Y-m-d H:i:s')."a.txt",$postXml);
        if (empty($postXml)) {
            return false;
        }
        $ruturnOut = json_encode(simplexml_load_string($postXml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $postObj = json_decode($ruturnOut);      // 将xml数据解析成对象

        // file_put_contents(__DIR__."/".date('Y-m-d H:i:s')."a1.txt",$ruturnOut);
        if ($postObj === false) {
            return false;
        }
        if (!empty($postObj->return_code)) {
            if ($postObj->return_code == 'FAIL') {
                return false;
            }
        }
        //	return $postObj;          // 返回结果对象；
        $order_number = $postObj->out_trade_no; //商户订单号

        //判断订单是否已经完毕，避免微信重复异步回调
        $result = Db::name('online_registration_order')->select('id', 'is_pay', 'user_id', 'account_id', 'price')->where('order_number', $order_number)->first();

        if (empty($result) || $result['is_pay'] != 1) {
            $return = '<xml>
                            <return_code><![CDATA[SUCCESS]]></return_code>
                            <return_msg><![CDATA[OK]]></return_msg>
                        </xml>';

            return $return;
            //订单不存在
            die;
        }

        //微信支付订单号
        $trade_no = $postObj->transaction_id;
        //订单支付时间
        $time_end = $postObj->time_end;
        //转换为时间戳
        $gtime = strtotime($time_end);
        $gmt_payment = date("Y-m-d H:i:s", $gtime); //转换为日期时间格式
        //买家微信支付分配的终端设备号，
        //  $buyer_id  = $postObj->device_info;
        //买家微信账号
        //	$buyer_login_id  = $_POST['buyer_login_id'];
        //订单总金额,订单总金额，单位为分
        $total_amount =  $postObj->total_fee;
        //实收金额,商家在交易中实际收到的款项
        $receipt_amount =  $postObj->total_fee; //微信的实收与总金额一致
        //付款金额,现金支付金额订单现金支付金额，详见支付金额
        $buyer_pay_amount =  $postObj->cash_fee;

        //此处编写回调处理逻辑
        $where = array(
            'order_number' =>  $order_number,
            'pay_time'    => $gmt_payment,
            'payment'    => 1,
            'trade_no'    => $trade_no,
            // 'buyer_id'		=> $buyer_id,
            'total_amount' => $total_amount,
            'receipt_amount' => $receipt_amount,
            'buyer_pay_amount' => $buyer_pay_amount,
        );
        //	file_put_contents(__DIR__."/b.txt",$where);
        //开启事务
        DB::beginTransaction();
        try {
            Db::name('online_registration_order')->where('id', $result['id'])->update(array('is_pay' => 2, 'change_time' => $gmt_payment));
            Db::name('online_registration_order_pay')->insert($where);

            //添加推送信息
            $onlineRegistrationPayInfoObj = new \app\port\controller\OnlineRegistrationPayInfo();
            $onlineRegistrationPayInfoObj->pushMsg($result);

            //获取读者证号
            $onlineRegistrationModelObj = new OnlineRegistrationModel();
            $onlineRegistrationModelObj->where('order_id', $result['id'])->update(array(
                'is_pay' => 2,
                'change_time' => $gmt_payment
            ));

            DB::commit();
            $return = '<xml>
                        <return_code><![CDATA[SUCCESS]]></return_code>
                        <return_msg><![CDATA[OK]]></return_msg>
                    </xml>';
            return $return; //响应表示业务处理成功，告知微信无需在异步通知
        } catch (\Exception $e) {
            DB::rollBack();
        }
        //处理成功一定要返回 success 这7个字符组成的字符串，
        //die('success');//响应success表示业务处理成功，告知微信无需在异步通知
    }
}
